#include<iostream>
#include"sharemem.h"

using namespace std;

int main(){
    cout<<"[in simdisk shell]\n";

    int running = 1;  
    void *shm = NULL;  
    struct shared_use_st *shared = NULL;  
    char buffer[BUFSIZ + 1];//用于保存输入的文本  
    int shmid;
    string line;
    //创建共享内存  
    shmid = shmget((key_t)2333, sizeof(struct shared_use_st), 0666|IPC_CREAT);  
    if(shmid == -1)  
    {  
        fprintf(stderr, "shmget failed\n");  
        exit(EXIT_FAILURE);  
    }  
    //将共享内存连接到当前进程的地址空间  
    shm = shmat(shmid, (void*)0, 0);  
    if(shm == (void*)-1)  
    {  
        fprintf(stderr, "shmat failed\n");  
        exit(EXIT_FAILURE);  
    }  
    printf("Memory attached at 0x%X\n", (long int)shm);  
    //设置共享内存  
    shared = (struct shared_use_st*)shm;  
    while(running)//向共享内存中写数据  
    {  
        //数据还没有被读取，则等待数据被读取,不能向共享内存中写入文本  
        while(shared->written == 1)  
        {  
            sleepms(200);  
            printf("Waiting...\n");  
        }  
        //向共享内存中写入数据
        printf("Enter cmd: \n");  
        getline(cin, line);
        strncpy(shared->cmd, line.c_str(), TEXT_SZ);
        //写完数据，设置written使共享内存段可读  
        shared->written = 1;  
        //输入了end，退出循环（程序）  
        if(line=="end"){
            running = 0;
            cout<<"end!!\n";
        }
            
    }  
    //把共享内存从当前进程中分离  
    if(shmdt(shm) == -1)  
    {  
        fprintf(stderr, "shmdt failed\n");  
        exit(EXIT_FAILURE);  
    }  
    sleep(1);  
    exit(EXIT_SUCCESS);  
}